package com.example.service.impl;

import com.example.document.EsItem;
import com.example.pojo.Item;
import com.example.repository.ItemRepository;
import com.example.service.EsItemService;
import com.example.utils.CopyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class EsItemServiceImpl implements EsItemService {
    @Autowired
    private ItemRepository itemRepository;

    @Override
    public EsItem queryById(Long id) {
        return itemRepository.findById(id).get();
    }

    @Override
    public List<EsItem> queryByPrefix(String keyWord) {
        Page<EsItem> byPrefix = itemRepository.findByPrefix(keyWord, null);
        return byPrefix.getContent();
    }

    @Override
    public void save(Item item) {
        EsItem copy = CopyUtil.copy(item, EsItem.class);
        itemRepository.save(copy);
    }

    @Override
    @Transactional
    public void update(Item item) {
        itemRepository.deleteById(item.getId());
        EsItem copy = CopyUtil.copy(item, EsItem.class);
        itemRepository.save(copy);
    }

    @Override
    public void deleteById(Long id) {
        itemRepository.deleteById(id);
    }
}
